const tokenManager = require("../classes/token.js");
const useropr = require("../classes/user.js");

exports.auth_check = function( token,  fn , next ){

    // 校验token
    tokenManager.verifyToken(token).then( tokenRes=>{
        
        if( !tokenRes.user_id ){
            next({
                status: 400,
                code: 400013,
                msg: "用户身份不存在"
            });
            return ;
        }
        // 检查用户是否已经退出
        useropr.checkUserStatus({userId: tokenRes.user_id}).then( 
            statusRes =>{
            if(statusRes.length == 0 ){
                next({
                    status: 500,
                    code: 500002,
                    msg: "用户状态检查，未找到用户"
                });
                return ;
            }
            if( statusRes[0].status == 1 ){
                // 用户已经退出
                next({
                    status : 400,
                    code: 400011,
                    msg: "用户已安全退出"
                });
                return ;
            }
             //校验通过 res为解码后的token内容
            fn( tokenRes.user_id ); // 解析后获取用户id
        }).catch( statusErr=>{
            
            next({
                status: 500,
                code: 500001,
                msg: "内部错误"
            });
        });
       
        
        return ;
    } ).catch( err=>{
        
        // token存在错误 , 过期的token, 假的token
        //确定jwt错误类型
        let errType = tokenManager.checkErrorAboutVerifyToken(err);
        
        //token过期
        if( errType.code == 400008 ){
           
            useropr.checkUserStatus({userId: err.userId}).then( statusRes =>{
                if(statusRes.length == 0 ){
                    next({
                        status: 500,
                        code: 500002,
                        msg: "用户状态检查，未找到用户"
                    });
                    return ;
                }
                if( statusRes[0].status == 0 ){
                
                //用户未退出
                next({
                        status: 400,
                        code: 400012,
                        msg:"token已失效"
                    });
                }else{
                    next({
                        status : 400,
                        code: 400011,
                        msg: "用户已安全退出"
                    });
                }
                return ;
            }).catch( statusErr =>{
                next({
                    status: 500,
                    code: 500002,
                    msg: statusErr
                });
                return ;
            });
            return ;
        }

        //token校验错误
        if(errType.refErr == "verifyTokenErr"){
            next(errType);
            return ;
        }
        
        //其他错误
        next({
            status: 500,
            code: 500002,
            msg: err
        })
        
    });


}